package course.d1228;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
3.1多线程卖票案例
  需求：用三个线程模拟三个售票窗口
  共同卖100张火车票

  解决重复卖票：
  第一种方法：
  同步代码块
  synchronize(锁对象){
//需要同步代码块
  }

  同步：  安全，执行效率低
  不同步：不安全，执行效率高

  第二种方法：
  同步方法：
  修饰符  synchronized 返回值类型  方法名(参数){
  //需要同步的代码
  }

 */
public class p2 {
    public static void main(String[] args) {
//        SaleTicket s = new SaleTicket();
//        Thread thread1 = new Thread(s, "窗口 1");
//        Thread thread2 = new Thread(s, "窗口 2");
//        Thread thread3 = new Thread(s, "窗口 3");
//        thread1.start();
//        thread2.start();
//        thread3.start();

//        SaleTicket1 s = new SaleTicket1();
//        Thread thread1 = new Thread(s,"A  ");
//        Thread thread2 = new Thread(s,"B  ");
//        Thread thread3 = new Thread(s,"C  ");
//        thread1.start();
//        thread2.start();
//        thread3.start();

        SaleTicket2 s = new SaleTicket2();
        Thread thread1 = new Thread(s,"A  ");
        Thread thread2 = new Thread(s,"B  ");
        Thread thread3 = new Thread(s,"C  ");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
//代码块
class SaleTicket implements Runnable {
    Object obj = new Object();
    int tickets = 200;

    @Override
    public void run() {
        while (tickets > 0) {
            synchronized (obj) {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "   正在售票第 " + (201 - tickets) + " 张票，还有 " + --tickets + " 张票");
                }
            }
        }
    }
    public static  synchronized void sy(Integer tickets){
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "   正在售票第 " + (201 - tickets) + " 张票，还有 " + --tickets + " 张票");
        }
    }
}
//同步方法
class SaleTicket1 implements Runnable{
    Object obj = new Object();
    int tickets = 200;
    @Override
    public void run() {
        while (tickets>0){
            sy();
        }
    }
    public synchronized void sy(){
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "   正在售票第 " + (201 - tickets) + " 张票，还有 " + --tickets + " 张票");
        }
    }
}
//Lock锁
class SaleTicket2 implements Runnable{
    int tickets = 200;
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
            while (tickets>0){
                //获取锁
                lock.lock();
                try {
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "   正在售票第 " + (201 - tickets) + " 张票，还有 " + --tickets + " 张票");
                }
                }finally {
                    //释放锁
                    lock.unlock();
                }
            }


    }
}
